shinnku's Blog

Trading Indicator

By shinnku on Jul 22, 2025

Trading Indicator

I will write about trading indicators in this post.

Both using technical analysis and fundamental analysis can help traders make informed decisions.

I will cover various types of indicators, with elaborate and fundamental math definitions.

Data types

GranularityTypical SchemaCommon Industry TermKey ContentsTypical Uses
MBO (Market‑By‑Order, L3)Schema::MboFull order‑book depth / Level 3Add, cancel, and execution events for every individual order, including order_idMarket making, trade‑match replay, liquidity research
MBP‑10 (Market‑By‑Price, L2)Schema::Mbp1010‑level price depthAggregated order size and updates at each of the top 10 price levelsOrder‑book dynamics, arbitrage modeling
MBP‑1 / TBBO (Top Book, L1)Schema::Mbp1Best bid/askBest bid and ask quotes plus accompanying tradesBasic quote display, NBBO comparison
TradesSchema::TradesTick‑by‑tick trades / last saleEvery executed trade (price, size, aggressor side, etc.)Price‑volume analysis, VWAP, trade‑driven strategies
OHLCV‑TSchema::OhlcvBars / K‑lineAggregated O‑H‑L‑C‑V data per second, minute, hour, or dayBacktesting, charting, low‑frequency signals

We now only use OHLCV‑T data, the other data types are used for high-frequency trading and are not available in our current setup.

Moving Averages (MA)

Simple Moving Average (SMA)

For a price (or data) series PtP_t and window length NN:

SMAN(t)=1Ni=0N1Pti\text{SMA}_N(t)=\frac{1}{N}\sum_{i=0}^{N-1} P_{t-i}
  • tt — index of the current bar (latest observation)
  • PtiP_{t-i} — value ii bars ago
  • NN — number of observations in the averaging window
indicator("ta.sma")

pine_sma(x, N) =>
    sum = 0.0
    for i = 0 to N - 1
        sum := sum + x[i] / N
    sum
plot(pine_sma(close, 15))

Exponentially Weighted Moving Average (EMA)

For a price series PtP_t and look‑back length NN (often called the “period”):

EMAN(t)=αPt+(1α)EMAN(t1),α=2N+1.\operatorname{EMA}_N(t)=\alpha P_t + (1-\alpha)\,\operatorname{EMA}_N(t-1), \qquad \alpha=\frac{2}{N+1}.
  • Recursive form (above) is how trading platforms update the line each new bar.
  • Expanded form—equivalent but shows the weights explicitly:
EMAN(t)=αi=0(1α)iPti.\operatorname{EMA}_N(t)=\alpha\sum_{i=0}^{\infty}(1-\alpha)^{i}P_{t-i}.

Because 0<1α<10 < 1-\alpha < 1, each older price is multiplied by a progressively smaller factor, so recent data dominate while the whole history still (theoretically) contributes.

indicator("ta.ema")

pine_ema(src, length) =>
    alpha = 2 / (length + 1)
    sum = 0.0
    sum := na(sum[1]) ? src : alpha * src + (1 - alpha) * nz(sum[1])
plot(pine_ema(close,15))
FormMeaningTypical use
na (bare constant)“Not‑available” — the Pine equivalent of NaN/null.Initialize a series when you deliberately want the first bar(s) to be empty.
na(x) (function)Returns true if x is na, otherwise false.Testing whether a previous‑bar value exists before you do math with it.

nz() means “not‑na, or zero”.

A simple moving average (SMA) assigns uniform weight inside its window and zero outside, so its lag to sudden jumps is fixed at roughly N/2N/2 bars. Because EMA weights decay, its effective window shortens automatically when volatility rises: large moves add more weight to the newest bar and less to the stale tail, pulling the EMA closer to price. That “elastic” lag gives the EMA its characteristic tighter hug to the price compared with an SMA of equal period.

Why the EMA curve “looks like that”

Exponential-decay weighting

The exponential moving average (EMA) of a series xtx_t with period NN can be written non-recursively as

EMAt=k=0wkxtk,wk=(1α)kα,α=2N+1.\mathrm{EMA}_t=\sum_{k=0}^{\infty} w_k x_{t-k}, \quad w_k=(1-\alpha)^k \alpha, \quad \alpha=\frac{2}{N+1} .

The weights wkw_k form a geometric (exponential) sequence that never quite reaches 00, so every past sample contributes, but each step back in time is worth a constant proportion ( 1α1-\alpha ) less than the one before.

Visual effect: the curve bends smoothly toward new prices, but the bend gets shallower the farther the new price is from the old EMA, because the distant tail of small weights damps the response.

First-order low-pass filter

is the discrete-time equivalent of the differential equation of a simple RC low-pass filter:

τdy(t)dt+y(t)=x(t)\tau \frac{d y(t)}{d t}+y(t)=x(t)

whose impulse response is et/τe^{-t / \tau}. That’s why the EMA curve has the same exponential relaxation shape when it pulls away from price spikes.

Moving Average Convergence Divergence (MACD)

The MACD is a momentum oscillator that shows the relationship between two EMAs of a security’s price.

By tracking how a short‑term EMA “converges toward” or “diverges from” a longer‑term EMA, it highlights changes in trend strength, direction, and momentum. Gerald Appel introduced it in the late 1970s, and the classic “12‑26‑9” parameters (explained below) remain the default today.

EventTypical readingNotes
Signal‑line crossoverDIF crosses above DEA → potential buy; crosses below → potential sellAkin to a two‑MA crossover system but applied to DIF vs. its own average. ([Wikipedia][1])
Zero‑line crossoverDIF moves from − to + → trend turns bullish; + to − → bearishConfirms shifts in medium‑term trend direction.
Histogram expansion / contractionGrowing bars = increasing momentum; shrinking bars = waning momentumGives an early visual cue before line crossovers.
Price / MACD divergencePrice makes higher highs while DIF makes lower highs (or vice‑versa)Can foreshadow trend reversals, but often produces early signals.

https://en.wikipedia.org/wiki/MACD

MACD line=EMA12EMA26\text{MACD line} =\mathrm{EMA}_{12}-\mathrm{EMA}_{26}

The signal line is then built as the exponential moving average of the MACD line:

Signal line=EMA9(MACD line)\text{Signal line} =\mathrm{EMA}_9(\text{MACD line})

macd_val  = ta.ema(close, 12) - ta.ema(close, 26)
signal    = ta.ema(macd_val, 9)
hist      = macd_val - signal

plot(macd_val,  color=color.blue,  title="MACD")
plot(signal,    color=color.orange,title="Signal")
plot(hist,      style=plot.style_histogram, title="Histogram")
Thanks for reading this far by Shinnku
© Copyright 2025 by Shinnku's blog. Built with ♥Astro.